import React, {Component} from 'react';
import request from '../../utils/request';
import {stringify} from 'qs';
import {baseServerUrl} from '../../utils/Constant';
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/title';
import 'echarts/lib/chart/bar';
import SearchForm from "../../components/AutoForm/SearchForm";
import {Card, DatePicker, Select, Spin, Input} from "antd";
import moment from "moment";

const { MonthPicker, RangePicker } = DatePicker;

class EchartsTest extends Component {

  state = {
    isLoading: true,
    searchFields: [{
      cols: [
        {
          md: 6,
          label: '客户名称',
          name: 'customName',
          component: <Input placeholder="请输入客户名称"/>
        },
        {
          md: 8,
          label: '创建时间',
          name: 'createTimeArray',
          component: <RangePicker format="YYYY-MM-DD" />,
        },{
          md: 4,
          label: '成本状态',
          name: 'outStatus',
          component: (
            <Select placeholder="请输入成本状态">
              <Option value="all">全部</Option>
              <Option value="payed">已支付</Option>
              <Option value="unpay">未支付</Option>
            </Select>
          ),
        },{
          md: 4,
          label: '收入状态',
          name: 'inStatus',
          component: (
            <Select placeholder="请输入收入状态">
              <Option value="all">全部</Option>
              <Option value="payed">已收款</Option>
              <Option value="unpay">未收款</Option>
            </Select>
          ),
        },
      ],
    }],
    searchValues: {},
  };

  handleSearchChange = fields => {
    const {searchValues} = this.state;
    this.setState({
      searchValues: {
        ...searchValues,
        ...fields
      }
    })
  };

  handleSearch = ()=>{
    this.setState({
      isLoading: true
    })
    const { searchValues } = this.state;
    let searchParam = {};
    Object.keys(searchValues).map(key => {

      if (key === 'createTimeArray') {
        const dateArray = searchValues[key]['value'];
        if (dateArray && dateArray.length) {
          let startTime = moment(dateArray[0]);
          let endTime = moment(dateArray[1]);
          searchParam[key] = [];
          searchParam[key].push(startTime.format('YYYY-MM-DD'));
          searchParam[key].push(endTime.format('YYYY-MM-DD'));
        }
      }else{
        searchParam[key] = searchValues[key]['value'];
      }
    });

    request(`${baseServerUrl}/tms/report/incomeBar?${stringify(searchParam)}`,{ method: 'GET'}).then(res => {
      this.setState({
        isLoading: false
      })
      const bar = echarts.init(document.getElementById("t2"));
      const seriesLabel = {
        normal: {
          show: true,
          textBorderColor: '#333',
          textBorderWidth: 2
        }
      }
      let xData = []
      let series = []
      let income = []
      let cost = []
      let incomeV = 0.00
      let costV = 0.00

      res.result.forEach(d => {
        xData.push(`${d.customName}\n利润：${(d.feeInSum - d.feeSum).toFixed(2)}`)
        income.push(d.feeInSum)
        cost.push(d.feeSum)
        incomeV += d.feeInSum
        costV += d.feeSum
      })
      series.push({
        name: '成本',
        type: 'bar',
        data: cost,
        label: seriesLabel,
      })
      series.push({
        name: '收入',
        type: 'bar',
        data: income,
        label: seriesLabel,
      })

      bar.setOption({
        title: {
          text: `收入、成本报表 利润：${(incomeV - costV).toFixed(2)}`
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['成本','收入']
        },
        grid: {
          left: 100
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {}
          }
        },
        yAxis: {
          type: 'value',
          name: '',
          axisLabel: {
            formatter: '{value}'
          }
        },
        xAxis: {
          type: 'category',
          inverse: true,
          data: xData,
        },
        series: series
      })
    })
  }

  componentDidMount() {
    this.handleSearch()
  }
  render() {
    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="利润报表"
          layout="inline"
          onFieldsChange={this.handleSearchChange}
          onSubmit={this.handleSearch}
          fields={this.state.searchFields}
          fieldValue={this.state.searchValues}
        />

        {
          this.state.isLoading ? <Spin size="large" style={{ marginLeft:  800}} /> : <div id="t2" style={{ width: "100%", height:  600}}></div>
        }

      </Card>
    );
  }
}

export default EchartsTest;
